const jsSHA = require('../utils/sha256.js');
const secretKey = 'f7dffabc-08ca-43dd-af4d-0b27aa05377f'

/**
 * 字典序排序
 * @param obj
 */
function objKeySort(obj) {
    let newObj = Object.keys(obj).sort();
    let newRes = ''

    for (let i in newObj) {
        newRes = newRes + newObj[i] + '=' + obj[newObj[i]] + '&'
    }

    return newRes
}

/**
 * sha256加密
 * @param val
 * @returns {ArrayBuffer}
 */
function getHash(val) {
    console.log('加密的参数：' + val)
    let shaObj = new jsSHA("SHA-256", "TEXT");
    shaObj.update(val)
    return shaObj.getHash("HEX");
}

/**
 * 时间戳
 * @returns {number}
 */
function timestampStr() {
    let tt = new Date().getTime() + ''
    return tt;
}

/**
 * 获取字符当前时间
 * @param date
 * @returns {string}
 */
function formatTime(date) {
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

/**
 * 格式化数字
 * @param n
 * @returns {string}
 */
function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}

/**
 * 调用微信登录
 */
function login(callback) {
    wx.login({
        success: function (res) {
            typeof callback == "function" && callback(res.code)
        },
        fail: function () {
            typeof callback == "function" && callback('error')
        }
    });
}

/**
 * request请求
 * @param url
 * @param data
 * @param method
 * @param callback
 */
function request(url, data, method, callback) {

    wx.request({
        url: url,
        data: handlerData(data),
        method: method,
        header: {
            'content-type': method == 'POST' ? 'application/x-www-form-urlencoded' : 'application/json',
            'token': wx.getStorageSync('token')
        },
        success: function (res) {
            typeof callback == "function" && callback(res.data)
        },
        error: function (res) {
            typeof callback == "function" && callback(res)
            wx.hideLoading()
        },
        complete: function () {
            wx.hideLoading()
        }
    });
}


function handlerData(data) {

    if (data == null) {
        data = {}
    }

    data['timestamp'] = timestampStr();
    data['randomStr'] = generateUUID()

    let newData = data

    let stringA = objKeySort(newData)

    // 加密的
    let signature = getHash(stringA + secretKey)

    data['signature'] = signature

    return data
}

/**
 * 生成UUID
 * @returns {string}
 */

function generateUUID() {
    let s = [];
    let hexDigits = "0123456789abcdef";
    for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid
}

function showErrorToast(msg) {
    wx.showToast({
        title: msg,
        image: '/static/icons/yichang.png'
    })
}

function showSuccessToast(msg) {
    wx.showToast({
        title: msg,
    })
}

//加   
function add(var1, var2) {
    var r1, r2, m;
    try {
        r1 = var1.toString().split(".")[1].length
    } catch (e) {
        r1 = 0
    }
    try {
        r2 = var2.toString().split(".")[1].length
    } catch (e) {
        r2 = 0
    }
    m = Math.pow(10, Math.max(r1, r2));
    return (var1 * m + var2 * m) / m;
}

//减
function sub(var1, var2) {
    var r1, r2, m, n;
    try {
        r1 = var1.toString().split(".")[1].length
    } catch (e) {
        r1 = 0
    }
    try {
        r2 = var2.toString().split(".")[1].length
    } catch (e) {
        r2 = 0
    }
    m = Math.pow(10, Math.max(r1, r2));
    //动态控制精度长度
    n = (r1 >= r2) ? r1 : r2;
    return ((var1 * m - var2 * m) / m).toFixed(n);
}

//乘
function mul(var1, var2) {
    var m = 0, s1 = var1.toString(), s2 = var2.toString();
    try {
        m += s1.split(".")[1].length
    } catch (e) {
    }
    try {
        m += s2.split(".")[1].length
    } catch (e) {
    }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}


//除
function div(var1, var2) {
    var t1 = 0, t2 = 0, r1, r2;
    try {
        t1 = var1.toString().split(".")[1].length
    } catch (e) {
    }
    try {
        t2 = var2.toString().split(".")[1].length
    } catch (e) {
    }

    r1 = Number(var1.toString().replace(".", ""));

    r2 = Number(var2.toString().replace(".", ""));
    return (r1 / r2) * Math.pow(10, t2 - t1);
}

module.exports = {
    formatTime,
    request,
    showErrorToast,
    showSuccessToast,
    login,
    timestampStr,
    getHash,
    objKeySort,
    generateUUID,
    handlerData,
    add,
    sub,
    mul,
    div,
}
